package client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.UnknownHostException;

public class ClientUdpReceiverThread implements Runnable {

	private boolean isRunning;
	private String username;
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public boolean isRunning() {
		return isRunning;
	}

	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}

	private DatagramSocket socket;
	
	public ClientUdpReceiverThread(DatagramSocket socket){
		this.socket = socket;
		this.isRunning = true;
	}
	
	@Override
	public void run() {
		try {

			byte[] buf = new byte[256];
			DatagramPacket packet;
			String fromServer;
			String outputLine;
			
			while(isRunning){
				packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);

				outputLine = "no output";
				fromServer = new String(packet.getData(), 0, packet.getLength());
				
				if (fromServer.startsWith("!new-bid")) {
					String[] splt = fromServer.split(" ");
					String desc = "";
					for (int i = 1; i < splt.length; i++) {
						if (i < splt.length - 1) {
							desc = desc + splt[i] + " ";
						} else {
							desc = desc + splt[i];
						}
					}
					
					outputLine = "You have been overbid on '" + desc + "'";
					
				} else if (fromServer.startsWith("!auction-ended")) {
					String[] splt = fromServer.split(" ");
					String winner, amount, desc;
					winner = splt[1];
					amount = splt[2];
					desc = "";
					
					for (int i = 3; i < splt.length; i++) {
						if (i < splt.length - 1) {
							desc = desc + splt[i] + " ";
						} else {
							desc = desc + splt[i];
						}
					}
					
					if (username.equals(winner)) {
						outputLine = "The auction '" + desc + "' has ended. You won with " + amount;
					} else {
						outputLine = "The auction '" + desc + "' has ended. " + winner + " won with " + amount;
					}
				}
				
				System.out.println(outputLine);
			}

		} catch (UnknownHostException e) {
			System.out.println("Error, couldn't find host");
		} catch (IOException e) {
			System.out.println("Error, couldn't read from UDP socket");
		}
	}
}
